from django.http import HttpResponse
from django.views.decorators.csrf import ensure_csrf_cookie


@ensure_csrf_cookie
def Email_Rand_Code(request):

    email = request.POST.get('email')
    def email_code(email):
        from django.core.mail import send_mail, send_mass_mail, EmailMultiAlternatives
        from django.conf import settings
        import random
        code_list = []
        for i in range(10):  # 0-9数字
            code_list.append(str(i))
        for i in range(65, 91):  # 对应从“A”到“Z”的ASCII码
            code_list.append(chr(i))
        for i in range(97, 123):  # 对应从“a”到“z”的ASCII码
            code_list.append(chr(i))
        myslice = random.sample(code_list, 6)  # 从list中随机获取6个元素，作为一个片断返回
        verification_code = ''.join(myslice)
        # 将随机的验证存在session表中，方便进行验证
        request.session['rand_code'] = verification_code
        # try:
        res = send_mail('教务系统找回密码',
                        '验证码1分钟内有效验：' + verification_code,
                        'haoqudian@163.com',
                        [email])
        print(res)
        if res != 1:
            static = '验证码发送失败'
            print('验证码发送失败')
        else:
            static = '验证码发送成功'
            print('验证码发送成功')

        return HttpResponse(static)
    email_code(email)